import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import ScreenSizeView from '@/views/ScreenSizeView.vue'
import NotFound from '@/views/NotFound.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: ScreenSizeView
    },
    {
      path: '/demo01',
      name: 'demo01',
      component: () => import('@/views/demo/demo01.vue')
    },
    // {
    //   path: '/demo02',
    //   name: 'demo02',
    //   component: () => import('@/views/demo/demo02.vue')
    // }
    // {
    //   path: '/demo03',
    //   name: 'demo03',
    //   component: () => import('@/views/demo/demo03.vue')
    // }
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
  ]
})
interface RouteInfo {
  name: string
  path: string
  component: string
}
async function loadRemoteRoue() {
  const routeInfoList: RouteInfo[] = [
    { name: 'demo02', path: '/demo02', component: '/views/demo/demo02.vue' }
    // { name: 'demo03', path: '/demo03', component: '/views/demo/demo03.vue' }
  ]
  return routeInfoList
}

const modules = import.meta.glob('@/views/**/*.vue') // 导入
// console.log('modules', modules)
function routeInfoToRouteRecordRaw(routeInfo: RouteInfo): RouteRecordRaw {
  const { name, path, component } = routeInfo
  let importPartPath = component.replace(/^\/+/, '') // 过滤字符串前面所有 '/' 字符
  importPartPath = importPartPath.replace(/\.\w+$/, '') // 去除.vue后缀名
  // console.log(
  //   'importPartPath',
  //   importPartPath,
  //   `/src/${importPartPath}.vue`,
  //   modules,
  //   modules[`/src/${importPartPath}.vue`]
  // )
  return {
    name,
    path,
    // component: () => import('@/' + importPartPath + '.vue')
    component: modules[`/src/${importPartPath}.vue`]
  }
}
let remoteRouteLoaded = false
router.beforeEach(async (to, from, next) => {
  // const { name: fromName, fullPath: fromFullPath } = from
  // const { name: toName, fullPath: toFullPath } = to
  // console.log(to, from)
  if (!remoteRouteLoaded) {
    remoteRouteLoaded = true
    const routeInfoList = await loadRemoteRoue()
    const retArr: RouteRecordRaw[] = routeInfoList.map((item) => routeInfoToRouteRecordRaw(item))
    retArr.forEach((item) => router.addRoute(item))
    // console.log(toName, router.hasRoute(toName as string))
    // next({ ...to, replace: true })
    next({ path: to.path, query: to.query, hash: to.hash, replace: true })
  } else {
    next()
  }
})

export default router
